package com.chuangfeng.framework.core.common.struts2.result;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import com.chuangfeng.framework.core.common.util.JsonUtil;
import com.chuangfeng.framework.core.common.util.StringUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;

/**
 * 自定义返回Json的视图类型
 * 使用说明：
 * 	如果在ACTION里面定义的objectName属性的话，那么给objectName赋值为一个JSONObject对象即可
 *  如果使用的是jsonTextVar的属性的话，那么jsonTextVar赋值应该是一个json字符串：如{"id":"1","content":["111",{"name":"xiedy","sex":"male","age":"20"},{"name":"xiedy","sex":"male","age":"20"}],"isFal":"true"}
 * @author xiedy
 *
 */
public class JsonResult implements Result, StrutsStatics {

	private static final Logger logger = Logger.getLogger(JsonResult.class);
	private static final long serialVersionUID = 1L;
	private String objectName;
	private String jsonTextVar;
	
	public void execute(ActionInvocation invocation) throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		final PrintWriter out = response.getWriter();
		try {
			response.setContentType("text/plain; charset=UTF-8"); 
			if(StringUtil.hasText(jsonTextVar)){
				Object jsonText = invocation.getStack().findValue(jsonTextVar);
				if(jsonText == null){
					out.write("{}"); 
				}else{
					out.write((String)jsonText);
				}
				out.close();
				return ;
			}
			Object object = invocation.getStack().findValue(objectName);
			if(object == null){
				out.write("{}"); 
			}else{
				out.write(JsonUtil.toJSONString(object));
			}
		} catch (Exception e) {
			logger.info(e.getMessage(), e);
			out.write("{error:"+e.getMessage()+"}"); 
		}
		out.close(); 
	}

	public String getObjectName() {
		return objectName;
	}

	public void setObjectName(String objectName) {
		this.objectName = objectName;
	}

	public String getJsonTextVar() {
		return jsonTextVar;
	}

	public void setJsonTextVar(String jsonTextVar) {
		this.jsonTextVar = jsonTextVar;
	}

}
